<?php

namespace App\Service\OpenShop\Feishu;

use App\Enums\BaseErrorCode;
use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Enums\OpenShop\InvestmentPromotion\SiteLocationEnum;
use App\Enums\OpenShop\InvestmentPromotion\SiteMissionEnum;
use App\Enums\OpenShop\InvestmentPromotion\UploadFileResourceEnum;
use App\Enums\OpenShop\InvestmentPromotion\UserIdentityCardEnum;
use App\Enums\OpenShop\Merchant\SiteMissionErrorTrait;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Exceptions\Custom\ResponseHttpException;
use App\Library\Rms\RmsShopApi;
use App\Models\OpenShop\InvestmentPromotion\OpenShopLogisticsInformationModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUploadFileResourceModel;
use App\Models\OpenShop\ShopEngineeringConstruction\OpenShopEngineeringConstructionModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Models\OpenShop\StartBusiness\OpenShopStartBusinessModel;
use App\Service\OpenShop\User\RmsUserService;
use App\Support\CustomForm\AttributeOpenShopSupport;
use App\Support\CustomForm\AttributeSupport;
use App\Support\CustomForm\ValidateSupport;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\Log;
use Kuafu\File\FileUtil;

class SiteMissionService
{
    /**
     * 获取任务详情
     *
     * @param int $id
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function info(int $id, array $orderPermission, int $userId)
    {
        $info = OpenShopSiteMissionModel::query()
                                        ->when(!$orderPermission['isAll'], function ($query) use ($userId) {
                                            $query->where('dealUid', $userId);
                                        })
                                        ->with('openShopSignOrderRel')
                                        ->with('openShopUserIdentityCardRel')
                                        ->where('id', $id)
                                        ->first();
        if (empty($info)) {
            return [];
        }


        // 用户列表
        $userInfo = RmsUserService::getRmsUserInfoByUserIds($info->dealUid);
        if (!empty($userInfo['data'][0])) {
            $userInfo = $userInfo['data'][0];
        } else {
            $userInfo = [];
        }

        $birthday = (string)optional($info->openShopUserIdentityCardRel)->birthday;
        $age      = (int)((time() - strtotime($birthday)) / (365 * 86400));
        if (empty($info->openShopUserIdentityCardRel->name)) {
            $applyUser = '暂无';
        } else {
            $applyUser = $info->openShopUserIdentityCardRel->name . "（" . UserIdentityCardEnum::GENDER[$info->openShopUserIdentityCardRel->gender] . "）（" . $age . "岁）";
        }
        return [
            'orderNo'     => $info->orderNo,
            'missionName' => (MainProcessEnum::MAIN_PROCESS_MAP[$info->mainStep] ?? '') . '-' . (MissionTemplateEnum::STEP_STATUS_TEXT[$info->stepStatus] ?? ''),
            'applyUser'   => $applyUser,
            'dealUid'     => $info->dealUid,
            'dealName'    => $userInfo['username'] ?? '',
            'stepStatus'  => $info->stepStatus,
            'status'      => $info->status,
            'completeAt'  => date('Y-m-d H:i:s', $info->completeAt)
        ];

    }

    /**
     * 加盟任务 首页 数据列表
     *
     * @param int $status
     * @param int $expiredAt
     * @param int $pageNum
     * @param int $pageSize
     * @return array
     */
    public static function paginateList(
        int $status,
        int $expiredStatus,
        int $pageNum,
        int $pageSize,
        array $orderPermission,
        int $userId,
        string $missionName,
        string $shopIds,
        string $handleUserId
    ): array {

        $baseQuery = OpenShopSiteMissionModel::query()
                                             ->where('isShow', 1)
                                             ->where('orderStatus', 1)
                                             ->where('handlerType', MissionTemplateEnum::HANDLER_TYPE_STAFF)
                                             ->when($missionName, function ($query) use ($missionName) {
                                                 $query->where('missionName', 'like', '%' . $missionName . '%');
                                             })
                                             ->when($shopIds, function ($query) use ($shopIds) {
                                                 $shopList = explode(',', $shopIds);
                                                 $orderNos = OpenShopMainProcessModel::query()
                                                                                     ->whereIn('shopId', $shopList)
                                                                                     ->select(['orderNo'])->get()
                                                                                     ->pluck('orderNo');
                                                 $query->whereIn('orderNo', $orderNos);
                                             })
                                             ->when($handleUserId, function ($query) use ($handleUserId) {
                                                 $query->where('dealUid', $handleUserId);
                                             });

        // 待处理
        $waitQuery = (clone $baseQuery)
            ->when(!$orderPermission['isAll'], function ($query) use ($userId) {

                // 待处理 - 除了超管只能看自己的
                $query->where('dealUid', $userId);
            });

        $waitDealCount = (clone $waitQuery)->where('status', SiteMissionEnum::STATUS_1)->count();

        $inTimeNumCount = (clone $waitQuery)->where('status', SiteMissionEnum::STATUS_1)
                                            ->where('expiredAt', '>', time())
                                            ->count();

        $oneDayTimeNumCount = (clone $waitQuery)->where('status', SiteMissionEnum::STATUS_1)
                                                ->where('expiredAt', '>', time())
                                                ->where('expiredAt', '<', time() + 86400)
                                                ->count();

        $expiredTimeNumCount = (clone $waitQuery)->where('status', SiteMissionEnum::STATUS_1)
                                                 ->where('expiredAt', '<', time())
                                                 ->count();

        // 已处理
        $hasQuery = (clone $baseQuery)
            ->when(!$orderPermission['isAll'], function ($query) use ($orderPermission) {

                // 已处理 - 显示和自己有关的
                $query->whereRaw($orderPermission['rawSql']);
            });

        $hasDealCount = (clone $hasQuery)->where('status', SiteMissionEnum::STATUS_2)->count();

        // 列表
        $paginator = (clone $baseQuery)
            ->when($status == SiteMissionEnum::STATUS_1, function ($query) use ($orderPermission, $userId) {

                // 待处理 - 除了超管只能看自己的
                if (!$orderPermission['isAll']) {
                    $query->where('dealUid', $userId);
                }
            })
            ->when($status == SiteMissionEnum::STATUS_2, function ($query) use ($orderPermission) {

                // 已处理 - 显示和自己有关的
                if (!$orderPermission['isAll']) {
                    $query->whereRaw($orderPermission['rawSql']);
                }
            })
            ->when($status != 0, function($query) use($status){
                $query->where('status', $status);
            })
            ->when($status == SiteMissionEnum::STATUS_1, function ($query) {
                $query->orderBy('expiredAt');
            })
            ->when($status == SiteMissionEnum::STATUS_2, function ($query) {
                $query->orderBy('completeAt', 'desc');
            })
            ->when($expiredStatus == 1, function ($query) { // 有效期内
                $query->where('expiredAt', '>', time());
            })
            ->when($expiredStatus == 2, function ($query) { // 差一天
                $query->where('expiredAt', '<', time() + 86400);
                $query->where('expiredAt', '>', time());
            })
            ->when($expiredStatus == 3, function ($query) { // 已过期
                $query->where('expiredAt', '<', time());
            })
            ->with('openShopSignOrderRel')
            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

        $allUserId   = [];
        $allShopCode = [];

        $paginator->each(function ($v) use (&$allUserId, &$allShopCode) {

            if (empty($v->openShopSignOrderRel)) {
                return;
            }

            if (!in_array($v->dealUid, $allUserId)) {
                $allUserId[] = $v->dealUid;
            }

//            if (!in_array($v->createdByUid, $allUserId)) {
//                $allUserId[] = $v->createdByUid;
//            }
//
//            if (!in_array($v->updatedByUid, $allUserId)) {
//                $allUserId[] = $v->updatedByUid;
//            }

            if (!in_array($v->openShopSignOrderRel->shopCode, $allShopCode)) {
                $allShopCode[] = $v->openShopSignOrderRel->shopCode;
            }
        });


        // 店铺列表
        $shopList = self::getRmsShopNameByCode($allShopCode, ['id', 'shopCode', 'name']);
        if (!empty($shopList['shopList'])) {
            $shopList = $shopList['shopList'];
            $shopList = array_column($shopList, null, 'shopCode');
        }

        // 用户列表
        $userList = RmsUserService::getRmsUserInfoByUserIds($allUserId);

        if (!empty($userList['data'])) {
            $userList = $userList['data'];
            $userList = array_column($userList, null, 'id');
        }

        $otherNum = [
            'waitDeal'       => $waitDealCount, // 待处理
            'hasDeal'        => $hasDealCount, // 已处理
            'inTimeNum'      => $inTimeNumCount, // 规定时间内
            'oneDayTimeNum'  => $oneDayTimeNumCount, // 还有 1 天到期
            'expiredTimeNum' => $expiredTimeNumCount, // 已过期
        ];

        return [
            'list'     => $paginator->map(function (OpenShopSiteMissionModel $log) use ($userList, $shopList) {
                $shopCode = (string)optional($log->openShopSignOrderRel)->shopCode;
                return [
                    'id'              => $log->id,
                    'missionType'     => $log->missionType,
                    'missionTypeText' => MissionTemplateEnum::MISSION_TYPE_TEXT[$log->missionType] ?? '',
                    'missionName'     => $log->missionName,
                    'status'          => $log->status,
                    'statusText'      => SiteMissionEnum::STATUS_TEXT[$log->status] ?? '',
                    'orderNo'         => $log->orderNo,
                    'dealUid'         => $log->dealUid,
                    'dealName'        => $userList[$log->dealUid]['username'] ?? '',
                    'shopName'        => $shopList[$shopCode]['name'] ?? '',
                    'shopCode'        => $shopCode,
                    'createdAt'       => $log->createdAt->format('Y-m-d H:i'),
                    'expiredAt'       => date('Y-m-d H:i', $log->expiredAt),
                    'completeAt'      => date('Y-m-d H:i:s', $log->completeAt)
                ];
            }),
            'count'    => $paginator->total(),
            'pageNum'  => $pageNum,
            'pageSize' => $pageSize,
            'otherNum' => $otherNum
        ];
    }

    /**
     * 生成新的任务
     *
     * @param string $orderNo
     * @param int $stepStatus
     * @return int|mixed
     */
    public static function genMission(string $orderNo, int $stepStatus, int $missionStatus = SiteMissionEnum::STATUS_1)
    {
        try {
            $stepStatusInfo           = MissionTemplateService::getByStepStatus($stepStatus);
            $openShopSiteMissionModel = new OpenShopSiteMissionModel();

            // 根据模板配置生成处理人
            $dealUid = (new MissionTemplateService)->getNextHandlerId($orderNo, $stepStatus);

            $openShopSiteMissionModel->missionId    = $stepStatusInfo->id;
            $openShopSiteMissionModel->missionType  = $stepStatusInfo->missionType;
            $openShopSiteMissionModel->mainStep     = $stepStatusInfo->mainStep;
            $openShopSiteMissionModel->stepStatus   = $stepStatusInfo->stepStatus;
            $openShopSiteMissionModel->missionName  = $stepStatusInfo->name;
            $openShopSiteMissionModel->status       = $missionStatus;
            $openShopSiteMissionModel->orderNo      = $orderNo;
            $openShopSiteMissionModel->dealUid      = $dealUid;
            $openShopSiteMissionModel->handlerType  = $stepStatusInfo->handlerType;
            $openShopSiteMissionModel->createdByUid = $dealUid;
            $openShopSiteMissionModel->updatedByUid = $dealUid;
            $openShopSiteMissionModel->expiredAt    = time() + $stepStatusInfo->handlerDay * 86400;
            $openShopSiteMissionModel->orderStatus  = SignOrderEnum::ORDER_STATUS_OK;

            // 隐藏任务显示
            $hiddenStep = [MissionTemplateEnum::STEP_STATUS_4, MissionTemplateEnum::STEP_STATUS_18];

            if (in_array($stepStatusInfo->stepStatus, $hiddenStep)) {
                $openShopSiteMissionModel->isShow = 0;
            }

            $openShopSiteMissionModel->save();

            return $openShopSiteMissionModel->id;

        } catch (\Exception $exception) {

            Log::channel('siteMission')->error('任务事件-新增任务处理失败:处理异常', [
                'orderNo'    => $orderNo,
                'stepStatus' => $stepStatus,
                'exception'  => $exception
            ]);

            handleException($exception, SiteMissionErrorTrait::$MISSION_CREATE_NEXT_FAIL);

            return 0;
        }


    }

    public const GET_SHOP_INFO_BY_CODE_URL = 'api/internal/shop/getShopByCodes';

    public static function getRmsShopNameByCode(array $codes, array $field = [], int $brandId = 1)
    {
        $codesStr = implode(',', $codes);
        $fieldStr = implode(',', $field);
        $url      = config('rms.domain') . self::GET_SHOP_INFO_BY_CODE_URL . '?shopCodes=' . $codesStr . '&brandId=1&fields=' . $fieldStr;
        $header   = getRmsReqHeader();
        $body     = "{}";
        $list     = getRmsMessageCommon("GET", $url, $body, $header, 'body');
        if (200 === ($list['code'] ?? null)) {
            return $list['data'];
        } else {
            return [];
        }

    }

    /**
     * 更新任务的状态
     *
     * @param $orderNo
     */
    public static function updateSiteMissionOrderStatus($orderNo)
    {
        // 判断是否存在
        $order = OpenShopSignOrderModel::query()
                                       ->where('orderNo', $orderNo)
                                       ->first();

        OpenShopSiteMissionModel::query()->where('orderNo', $orderNo)
                                ->update([
                                    'orderStatus' => $order->status,
                                ]);
    }

    /**
     * 关闭支付任务
     * @param string $orderNo
     * @param int $stepStatus
     * @return bool
     */
    public static function closePayCloseMission(string $orderNo, int $stepStatus): bool
    {
        // 仅支持设计、软装订单支付的取消
        if (!in_array($stepStatus, [MissionTemplateEnum::STEP_STATUS_14, MissionTemplateEnum::STEP_STATUS_17, MissionTemplateEnum::STEP_STATUS_16])) {
            return false;
        }

        // 判断当前阶段
        $nowStepStatus = OpenShopMainProcessModel::query()->where('orderNo', $orderNo)->value('nowStepStatus');
        $nowStepStatusSort = MissionTemplateService::getSortByStepStatus($nowStepStatus);

        $doStepStatus = MissionTemplateService::getSortByStepStatus($stepStatus);

        // 只有流程走到后面了，才能关任务
        if ($nowStepStatusSort >= $doStepStatus) {
            return (bool)OpenShopSiteMissionModel::delMission($orderNo, $stepStatus);
        }

        return false;
    }

    private static function miniMissionBuilder(int $status, array $orderPermission, int $userId, string $search)
    {
        $shopCode = 0;
        $username = '';
        if ($search) {
            if (preg_match("/^\d+$/", $search)) {

                // 纯数字，即店铺号
                $shopCode = (int)$search;
            } else {

                // 老板姓名
                $username = (string)$search;
            }
        }

        return OpenShopSiteMissionModel::query()
                                       ->when($status == SiteMissionEnum::STATUS_1,
                                           function ($query) use ($orderPermission, $userId) {

                                               // 待处理 - 除了超管只能看自己的
                                               if (!$orderPermission['isAll']) {
                                                   $query->where('dealUid', $userId);
                                               }
                                           })
                                       ->when($status == SiteMissionEnum::STATUS_2 && $orderPermission['rawSql'],
                                           function ($query) use ($orderPermission) {

                                               // 已处理 - 显示和自己有关的
                                               $query->whereRaw("open_shop_site_mission." . $orderPermission['rawSql']);
                                           })
                                       ->where('open_shop_site_mission.isShow', 1)
                                       ->where('open_shop_site_mission.orderStatus', 1)
                                       ->whereIn('open_shop_site_mission.stepStatus',
                                           MissionTemplateEnum::OPEN_MISSION_LISTS)
                                       ->where('open_shop_site_mission.status', $status)
                                       ->when($status == SiteMissionEnum::STATUS_1, function ($query) {
                                           $query->orderBy('expiredAt');
                                       })
                                       ->when($status == SiteMissionEnum::STATUS_2, function ($query) {
                                           $query->orderByDesc('completeAt');
                                       })
                                       ->when($shopCode, function ($query) use ($shopCode) {
                                           $query->join('open_shop_sign_order as order', 'order.orderNo',
                                               'open_shop_site_mission.orderNo')
                                                 ->where('shopCode', $shopCode);
                                       })
                                       ->when($username, function ($query) use ($username) {
                                           $query->join('open_shop_main_process as process', 'process.orderNo', '=',
                                               'open_shop_site_mission.orderNo')
                                                 ->join('open_shop_user_identity_card as identity',
                                                     'identity.orderNo', '=', 'process.orderNo')
                                                 ->where('identity.name', 'like', "%{$username}%")
                                                 ->addSelect('process.id', 'identity.name');
                                       })
                                       ->select('open_shop_site_mission.*');
    }

    public static function miniMissionListsCount(array $orderPermission, int $userId, string $search): array
    {
        return [
            [
                'status' => $status = SiteMissionEnum::STATUS_1,
                'count'  => self::miniMissionBuilder($status, $orderPermission, $userId, $search)->count(),
            ],
            [
                'status' => $status = SiteMissionEnum::STATUS_2,
                'count'  => self::miniMissionBuilder($status, $orderPermission, $userId, $search)->count(),
            ],
        ];
    }

    /**
     * 夸父开店小程序的任务列表
     * @param int $status
     * @param int $pageNum
     * @param int $pageSize
     * @param int $scope
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function miniMissionLists(
        int $status,
        int $pageNum,
        int $pageSize,
        array $orderPermission,
        int $userId,
        string $search
    ) {
        $paginates = self::miniMissionBuilder($status, $orderPermission, $userId, $search)
                         ->with(['openShopUserIdentityCardRel', 'addressRel'])
                         ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

        $dealUids      = collect($paginates->items())->pluck('dealUid')->toArray();
        $dealUserInfos = collect(RmsUserService::getRmsUserInfoByUserIds($dealUids)['data'] ?? [])->keyBy('id');

        $lists = collect($paginates->items())->map(function ($item) use ($dealUserInfos) {
            $dealUserInfo = $dealUserInfos[$item['dealUid']] ?? [];

            return [
                'id'            => $item->id,
                'orderNo'       => $item->orderNo,
                'stepStatus'    => $item->stepStatus,
                'missionName'   => $item->missionName,
                'merchantName'  => (string)optional($item->openShopUserIdentityCardRel)->name,
                'addressPrefix' => (string)optional($item->addressRel)->addressPrefix ?: '-',
                'dealUid'       => $item->dealUid,
                'dealName'      => $dealUserInfo['username'] ?? $item['dealUid'],
                'expiredAt'     => $item->expiredAt ? date('Y-m-d', $item->expiredAt) : '-',
                'status'        => $item->status,
                'statusText'    => SiteMissionEnum::STATUS_TEXT[$item->status] ?? '',
            ];
        });


        return [
            'count'    => $paginates->total(),
            'pageNum'  => $pageNum,
            'pageSize' => $pageSize,
            'list'     => $lists,
        ];
    }

    public static function siteInfo(int $id)
    {
        $siteMission = OpenShopSiteMissionModel::query()
                                               ->with('openShopSignOrderRel', 'openShopUserIdentityCardRel',
                                                   'addressRel')
                                               ->find($id);
        if (!$siteMission) {
            throw new ResponseHttpException(BaseErrorCode::$MISSION_INFO_GET_FAIL);
        }

        $birthday = (int)optional($siteMission->openShopUserIdentityCardRel)->birthday;
        if ($birthday) {
            $age = date('Y') - ((int)date('Y', strtotime($birthday)));
        } else {
            $age = 0;
        }


        return [
            'orderNo'           => $siteMission->orderNo,
            'missionName'       => (MainProcessEnum::MAIN_PROCESS_MAP[$siteMission->mainStep] ?? '') . ' - ' . $siteMission->missionName,
            'userName'          => (string)optional($siteMission->openShopUserIdentityCardRel)->name,
            'gender'            => rtrim(UserIdentityCardEnum::GENDER[(int)optional($siteMission->openShopUserIdentityCardRel)->gender] ?? '男',
                '性'),
            'age'               => $age,
            'shopCode'          => (string)optional($siteMission->openShopSignOrderRel)->kfShopCode,
            'shopAddressPrefix' => (string)optional($siteMission->addressRel)->addressPrefix ?: '-',
            'expiredAt'         => date('Y-m-d H:i:s', $siteMission->expiredAt),
            'createdAt'         => $siteMission->createdAt->toDateTimeString(),
            'status'            => $siteMission->status,
            'stepStatus'        => $siteMission->stepStatus,
        ];
    }

    public static function buildInfo($orderNo)
    {
        //查看选址表单
        $siteLocationModel = OpenShopSiteLocationModel::query()
                                                      ->with(['baseUserInfoRel', 'identityCardRel'])
                                                      ->where('orderNo', $orderNo)
            ->whereIn('source',
                [
                    OpenShopSiteLocationModel::SOURCE_OPEN_SHOP,
                    OpenShopSiteLocationModel::SOURCE_HOUSING
                ])
                                                      ->first();
        //获取门店名称
        $shopName = (new RmsShopApi)->getShopByCode(OpenShopSignOrderModel::query()->where('orderNo', $orderNo)->value('shopCode'))['data']['name'] ?? '';
        //获取物流信息建档的数据
        $logisticsInfo = OpenShopLogisticsInformationModel::query()
                                                          ->where('orderNo', $orderNo)
                                                          ->first();

        $shopCheckAccept = ShopCheckAcceptService::detail($orderNo)["detail"];


        if ($siteLocationModel == null) {
            $buildInfo = [
                'shopName'      => $shopName,
                'userInfo'      => '-',
                'address'       => '-',
                'area'          => '-',
                'origin'        => '-',
                'openTime'      => '-',
                'receiverName'  => '-',
                'phoneNumber'   => '-',
                'regions'       => [
                    'provinceCode'  => 0,
                    'cityCode'      => 0,
                    'districtCode'  => 0,
                    'addressPrefix' => '',
                ],
                'addressDetail' => '-',
                'manageId'      => 0,
                'managerName'   => ''
            ];
        } else {
            $buildInfo = [
                'shopName'      => $shopName,
                'userInfo'      => $siteLocationModel->identityCardRel->name . ' | ' . $siteLocationModel->baseUserInfoRel->mobile,
                'address'       => $siteLocationModel->address,
                'area'          => $siteLocationModel->area . '㎡',
                'origin'        => SiteLocationEnum::MESSAGE_FROM_TYPE_TEXT[$siteLocationModel->messageFrom] ?? '-',
                'openTime'      => formatDate($siteLocationModel->openTime),
                //物流建档的数据
                'receiverName'  => $logisticsInfo->receiverName ?? $siteLocationModel->identityCardRel->name,
                'phoneNumber'   => $logisticsInfo->phoneNumber ?? $siteLocationModel->baseUserInfoRel->mobile,
                'regions'       => [
                    'provinceCode'  => $logisticsInfo->provinceCode ?? $siteLocationModel->provinceCode,
                    'cityCode'      => $logisticsInfo->cityCode ?? $siteLocationModel->cityCode,
                    'districtCode'  => $logisticsInfo->areaCode ?? $siteLocationModel->areaCode,
                    'addressPrefix' => $logisticsInfo->regions ?? $siteLocationModel->cityArea,
                ],
                'addressDetail' => $logisticsInfo->addressDetail ?? $siteLocationModel->address,
            ];
            if (!empty($shopCheckAccept)) {
                $buildInfo['manageId']    = $shopCheckAccept->manageId;
                $buildInfo['managerName'] = $shopCheckAccept->managerName;
            }
        }


        return [
            'buildInfo' => $buildInfo
        ];
    }

    public static function constructionInput($orderNo)
    {
        $res = [];
        //获得筹备部确认施工完成
        $detail = OpenShopEngineeringConstructionModel::query()
                                                      ->where('orderNo', $orderNo)
                                                      ->with([
                                                          'attachRel' => function ($query) {
                                                              $query->whereIn("position",
                                                                  array_keys(UploadFileResourceEnum::ENGINEERING_CONSTRUCTION_MAP))
                                                                    ->where("isDeleted", 0);
                                                          }
                                                      ])
                                                      ->first();
        //处理图片
        $shopHeaderImages   = '';
        $shopInnerImages    = '';
        $shopOutNightImages = '';
        if ($detail->attachRel != null) {
            foreach ($detail->attachRel as $value) {
                if ($value->position == UploadFileResourceEnum::ENGINEERING_CONSTRUCTION_1) {
                    $shopHeaderImages = $value->formatUrl;
                }
                if ($value->position == UploadFileResourceEnum::ENGINEERING_CONSTRUCTION_2) {
                    $shopInnerImages = $value->formatUrl;
                }
                if ($value->position == UploadFileResourceEnum::ENGINEERING_CONSTRUCTION_3) {
                    $shopOutNightImages = $value->formatUrl;
                }
            }
        }
        $res[] = AttributeSupport::getInstance('engineeringConstructionStartTime', AttributeSupport::INPUT_DATE,
            '施工进场时间')
                                 ->setValue($detail->engineeringConstructionStartTime)
                                 ->setCustomAttribute(['disabled', true])
                                 ->setValidateRules(ValidateSupport::getInstance(true))
                                 ->build();
        $res[] = AttributeSupport::getInstance('engineeringConstructionFinishTime', AttributeSupport::INPUT_DATE,
            '施工完成时间')
                                 ->setValue($detail->engineeringConstructionFinishTime)
                                 ->setCustomAttribute(['icon', 'arrow-right'])
                                 ->setValidateRules(ValidateSupport::getInstance(true))
                                 ->build();
        $res[] = AttributeSupport::getInstance('finishStatus', AttributeSupport::INPUT_TYPE_SELECT, '施工完成状态')
                                 ->setValue($detail->finishStatus == 0 ? '' : $detail->finishStatus)
                                 ->setCustomAttribute(['icon', 'arrow-right'])
                                 ->setValidateRules(ValidateSupport::getInstance(true))
                                 ->setCustomAttribute([
                                     'options',
                                     AttributeOpenShopSupport::setSelectOptions(OpenShopEngineeringConstructionModel::FINISH_STATUS_MAP)
                                 ])
                                 ->build();
        $res[] = AttributeSupport::getInstance('shopHeaderImages', AttributeOpenShopSupport::ALBUM_RADIO, '门店门头实景拍摄图')
                                 ->setValue(function () use ($shopHeaderImages) {
                                     if (mb_strlen($shopHeaderImages)) {
                                         return [$shopHeaderImages];
                                     } else {
                                         return $shopHeaderImages;
                                     }
                                 })
                                 ->setCustomAttribute([
                                     'descImg',
                                     'https://img.51kuafu.com/1/0/1b06c33090d9a05b933978f690a5e564.png'
                                 ])
                                 ->build();
        $res[] = AttributeSupport::getInstance('shopInnerImages', AttributeOpenShopSupport::ALBUM_RADIO, '门店室内实景拍摄图')
                                 ->setValue(function () use ($shopInnerImages) {
                                     if (mb_strlen($shopInnerImages)) {
                                         return [$shopInnerImages];
                                     } else {
                                         return $shopInnerImages;
                                     }
                                 })
                                 ->setCustomAttribute([
                                     'descImg',
                                     'https://img.51kuafu.com/1/0/e40c9b3a454e628a6af797ad4b5c1de8.png'
                                 ])
                                 ->build();
        $res[] = AttributeSupport::getInstance('shopOutNightImages', AttributeOpenShopSupport::ALBUM_RADIO,
            '夜间门店室内实景拍摄图')
                                 ->setValue(function () use ($shopOutNightImages) {
                                     if (mb_strlen($shopOutNightImages)) {
                                         return [$shopOutNightImages];
                                     } else {
                                         return $shopOutNightImages;
                                     }
                                 })
                                 ->setCustomAttribute([
                                     'descImg',
                                     'https://img.51kuafu.com/1/0/e247e71737da1c863b913e5ffd7b3bfc.png'
                                 ])
                                 ->build();

        return $res;
    }

    //获得施工时间
    public static function constructionInfo($orderNo)
    {
        return [
            'time' => formatDateYmd(OpenShopEngineeringConstructionModel::query()->where('orderNo', $orderNo)
                                                                        ->value('engineeringConstructionStartTime'))
        ];
    }

    //筹备部确认施工完成表单实时保存
    public static function constructionUpdate(array $params, $userInfo)
    {
        $data    = [];
        $fileArr = [];
        foreach ($params as $k => $param) {
            if ($k == 'orderNo') {
                continue;
            }
            if (is_array($param)) {  //处理文件特殊情况
                $fileArr[$k] = $param[0] ?? '';
            } elseif (mb_strlen($param) > 1) {  //Ymd转时间戳
                $data[$k] = strtotime($param);
            } else {
                $data[$k] = $param;
            }
        }
        $orderNo = $params['orderNo'];
        //处理文件修改
        if (count($fileArr)) {
            foreach ($fileArr as $k => $item) {
                //根据 $k 转化为 position
                foreach (UploadFileResourceEnum::ENGINEERING_CONSTRUCTION_MAP as $key => $value) {
                    if ($k == $value) {
                        //position = $key
                        if (mb_strlen($item)) {
                            $model               = OpenShopUploadFileResourceModel::firstOrNew([
                                'orderNo'  => $orderNo,
                                'position' => $key,
                            ]);
                            $model->url          = str_replace(FileUtil::domain(), '', $item);
                            $model->isPublic     = 1;
                            $model->createdAt    = time();
                            $model->createdByUid = $userInfo->userId;
                            $model->save();
                        } else {
                            OpenShopUploadFileResourceModel::query()->where([
                                'orderNo'  => $orderNo,
                                'position' => $key,
                            ])->delete();
                        }
                    }
                }
            }
        } else {
            unset($data['orderNo']);
            OpenShopEngineeringConstructionModel::query()
                                                ->where('orderNo', $orderNo)
                                                ->update(array_merge($data, [
                                                    'updatedByUid' => $userInfo->userId,
                                                    'updatedAt'    => time()
                                                ]));
        }
    }
}
